/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.icee.myth.utils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

/**
 *
 * @author liuxianke
 */
public class DESUtil {

    public static String encrypt(String str, String key) {
        try {
            DESedeKeySpec keyspec = new DESedeKeySpec(key.getBytes());
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
            SecretKey sKey = keyfactory.generateSecret(keyspec);

            Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
            cipher.init(Cipher.ENCRYPT_MODE, sKey);
            byte[] res = cipher.doFinal(nullPadByteArray(str.getBytes(), 8));
            return Base64.encodeBase64String(res).trim();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    // 用0值填充字节数组至某数值对齐
    public static byte[] nullPadByteArray(byte[] bytes, int mul) {
        int len = bytes.length;
        int n = (len + mul - 1) / mul * mul;
        byte[] res = new byte[n];
        for (int i = 0; i < len; i++) {
            res[i] = bytes[i];
        }
        return res;
    }
}
